/**
 * 
 */
package org.compiere.process;

import java.io.File;
import java.io.FileInputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;

import org.compiere.Adempiere;
import org.compiere.db.CConnection;
import org.compiere.util.CLogMgt;
import org.compiere.util.Env;
import org.compiere.util.Ini;
import org.compiere.util.Msg;
import org.compiere.util.WebEnv;

import extend.org.compiere.utils.Util;

/**
 * @author V.Sokolov
 *
 */
public class BPMFormsSubs extends SvrProcess {

	/* Current context		*/
	private Properties m_ctx;
	/* */
	
	int p_BPM_VersionBudget_ID;
	
	String url;
	StringBuffer param = new StringBuffer("/budget/forms.action");
	
	/* 
	 */
	@Override
	protected void prepare() {
		
		log.info(" Subs Data Forms ");
		m_ctx = Env.getCtx();
		
		ProcessInfoParameter[] para = getParameter();
		for(int i = 0; i < para.length; i++) {
			String name = para[i].getParameterName();
			if (para[i].getParameter() == null)
				;
			else if (name.equals("BPM_VersionBudget_ID"))
				p_BPM_VersionBudget_ID = para[i].getParameterAsInt();
			else
				log.log(Level. SEVERE, "Unknown Parameter: " + name);
		}
		
		if (Thread.currentThread().getStackTrace().length>10) {
			String envName = Ini.getAdempiereHome();
			if (envName == null)
				return;
			envName += File.separator + "AdempiereEnv.properties";
			File envFile = new File(envName);
			if (!envFile.exists())
			return;
			
			Properties env = new Properties();
	 		try
	 		{
				FileInputStream in = new FileInputStream(envFile);
				env.load(in);
				in.close();
	 		}
	 		catch (Exception e)
	 		{
				return;
			}
			url="http://"+env.getProperty("ADEMPIERE_WEB_ALIAS");	
		}
		else {
			CConnection cc = CConnection.get();
			url="http://"+cc.getAppsHost();		
		}
	}

	/* 
	 */
	@Override
	protected String doIt() throws Exception {
		
		if(url.startsWith("http"))
			Env.startBrowser(url+param+"?verbudgetID=" + p_BPM_VersionBudget_ID + "&userID="+Env.getAD_User_ID(m_ctx));
		
		return Msg.translate(m_ctx, "Success");
	}
	
	private String getHttpHost(){
		
		if(Ini.getCodeBase() != null)
			return "http://" + Ini.getCodeBase().getHost();
		else
			return Util.getHostHttp();
		 
	}

}
